<template>
  <el-divider style="width: 100%"
    ><span style="font-size: 23px; font-family: '楷体'">面试管理</span></el-divider
  >
  <el-form :inline="true" style="margin-left: 70%">
    <el-form-item v-if="searchIntv.intvState === '未面试'">
      <el-upload
        action="/api/admin/import/excelImportIntv"
        :headers="token"
        name="file"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        :on-success="successUpload"
      >
        <template #trigger>
          <el-button type="primary"
            ><el-icon style="margin-right: 5px" size="18px"><Download /></el-icon
            >导入面试信息表</el-button
          >
        </template>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="exportIntvInfo"
        ><el-icon style="margin-right: 5px" size="18px"><Upload /></el-icon
        >导出面试信息表</el-button
      >
    </el-form-item>
  </el-form>
  <!--  搜索-->
  <el-form :inline="true" :model="searchIntv">
    <el-form-item label="学号">
      <el-input
        v-model="searchIntv.studentId"
        type="text"
        placeholder="输入学号"
        clearable
        style="width: 130px"
      />
    </el-form-item>
    <el-form-item label="姓名">
      <el-input
        v-model="searchIntv.stuName"
        type="text"
        placeholder="输入姓名"
        clearable
        style="width: 100px"
      />
    </el-form-item>
    <el-form-item label="卓越班班级">
      <el-select
        v-model="searchIntv.className"
        placeholder="选择卓越班名称"
        style="width: 190px"
        clearable
      >
        <el-option v-for="item in classNameList" :label="item.value" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="预约面试时间">
      <el-date-picker
        v-model="searchIntv.intvDate"
        placeholder="选择预约面试日期"
        clearable
        :disabled-date="intvDisabledDateFun"
        style="width: 180px"
      />
    </el-form-item>
    <el-form-item label="分数筛选">
      <el-input-number
        v-model="searchIntv.intvScore"
        :min="0"
        :max="100"
        controls-position="right"
        clearable
        style="width: 90px"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm">搜索</el-button>
      <el-button type="info" @click="resetForm">清空</el-button>
    </el-form-item>
  </el-form>

  <el-row v-if="searchIntv.intvState === '已面试'">
    <el-button type="success" @click="passByIntvIds">批量通过</el-button>
    <el-button type="danger" @click="noPassByIntvIds">批量不通过</el-button> </el-row
  ><br />

  <el-tabs @tab-change="handleClick" v-model="searchIntv.intvState" style="margin-top: -20px">
    <el-tab-pane label="未面试" name="未面试"></el-tab-pane>
    <el-tab-pane label="已面试" name="已面试"></el-tab-pane>
    <el-tab-pane label="未通过" name="未通过"></el-tab-pane>
    <el-tab-pane label="已通过" name="已通过"></el-tab-pane>
  </el-tabs>

  <!--  表单-->
  <el-table
    :data="intvInfoData"
    border
    @selection-change="handleSelectionChange"
    @sort-change="sortByStuGrade"
  >
    <el-table-column v-if="searchIntv.intvState === '已面试'" type="selection" width="40" />
    <el-table-column type="index" label="序号" width="60" align="center" />
    <el-table-column prop="studentId" label="学号" width="130" align="center" />
    <el-table-column prop="stuName" label="姓名" width="90" align="center" />
    <el-table-column prop="stuSpeciality" label="专业" align="center" />
    <el-table-column prop="stuGrade" label="年级" width="90" align="center" sortable="custom" />
    <el-table-column prop="stuClass" label="班级" align="center" />
    <el-table-column prop="className" label="卓越班班级" align="center" />
    <el-table-column prop="intvDate" label="预约面试日期" width="140" align="center" sortable />
    <el-table-column prop="intvTime" label="面试时间" width="110" align="center" sortable />
    <el-table-column prop="intvScore" label="面试分数" width="110" align="center" sortable>
      <template v-slot="row">
        <span v-if="row.row.intvScore != '' && row.row.intvScore != null">{{
          row.row.intvScore
        }}</span>
        <span v-else>无</span>
      </template>
    </el-table-column>
    <el-table-column prop="intvState" label="面试状态" width="90" align="center" />
    <el-table-column
      label="操 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;作"
      width="240"
      align="center"
    >
      <template v-slot="{ row }">
        <el-button type="primary" @click="goDetail(row)">详情</el-button>
        <el-button type="warning" @click="setScore(row)">打分</el-button>
        <el-button
          v-if="{ ...row }.intvState == '未通过' || { ...row }.intvState == '已通过'"
          type="danger"
          @click="Return(row)"
          >撤回</el-button
        ><br />
        <el-button
          v-if="{ ...row }.intvState == '已面试'"
          type="success"
          @click="pass(row)"
          style="margin-top: 5px; margin-left: 15px"
          >通过</el-button
        >
        <el-button
          v-if="{ ...row }.intvState == '已面试'"
          type="danger"
          @click="noPass(row)"
          style="margin-top: 5px"
          >不通过</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!--  分页-->
  <br />
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[10, 20, 30, 40, 50]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    background
    @size-change="SizeChange"
    @current-change="CurrentChange"
  />

  <!--  详情对话框-->
  <el-dialog
    v-model="dialogDetailVisible"
    align-center
    center
    title="学生详细信息"
    width="50%"
    style="height: 700px; background-color: #d1edc4"
  >
    <div class="info-box">
      <div class="item-box">
        <el-image
          v-if="diaForm.stuImage"
          style="width: 100px;display: block; float: left"
          :src="diaForm.stuImage"
        />
        <div
          v-else
          style="
          width: 100px;height: 150px;display: flex; float: left;
          background-color: #fff;align-items: center;justify-content: center;">
          无照片
        </div>
        <span class="label">姓名：</span>
        <span class="des">{{ diaForm.stuName }}</span>

        <span class="label">性别：</span>
        <span class="des">{{ diaForm.stuSex }}</span>

        <span class="label">学号：</span>
        <span class="des">{{ diaForm.studentId }}</span>

        <span class="label">电话：</span>
        <span class="des">{{ diaForm.stuPhone }}</span>

        <br />
        <span class="label">学院：</span>
        <span class="des">{{ diaForm.stuDepartment }}</span>

        <span class="label">专业：</span>
        <span class="des">{{ diaForm.stuSpeciality }}</span>

        <span class="label">年级：</span>
        <span class="des">{{ diaForm.stuGrade }}</span>

        <br />
        <span class="label">班级：</span>
        <span class="des">{{ diaForm.stuClass }}</span>

        <span class="label">邮箱：</span>
        <span class="des">{{ diaForm.email }}</span>

        <br />
        <span class="label">竞赛信息：</span>
        <div
          v-if="diaForm.contest != null && diaForm.contest != ''"
          style="color: #333333; margin-left: 80px"
          v-for="(item, index) in diaForm.contest"
          :key="index"
        >
          <div>
            奖项{{ index + 1 }}：{{
              item.conName + '&nbsp;&nbsp;&nbsp;&nbsp;获奖时间：' + item.conTime
            }}<br />
          </div>
        </div>
        <span v-else>无<br /></span>

        <span class="label">个人技能：</span>
        <span class="des">{{ diaForm.stuSkill + '，' + diaForm.stuSkillStack }}</span>

        <br />
        <span class="label">个人意向：</span>
        <span class="des">{{ diaForm.stuIntention }}</span>
      </div>
    </div>
  </el-dialog>

  <!--  打分对话框-->
  <el-dialog v-model="dialogScoreVisible" align-center center title="面试成绩打分" width="30%">
    <el-form ref="scoreFormRef" :model="intvScoreInfo" label-width="100px">
      <el-form-item
        label="面试分数"
        prop="intvScore"
        :rules="[
          { required: true, message: '请填写分数' },
          { type: 'number', message: '分数必须是一个数字' }
        ]"
      >
        <el-input v-model.number="intvScoreInfo.intvScore" type="text" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="dialogScoreVisible = false">取消</el-button>
        <el-button type="primary" @click="submitScore(scoreFormRef)">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { h, onMounted, ref } from 'vue'
import { getIntvInfo, setIntvScore, noPassByIds, passByIds, ExportIntvInfo } from '@/apis/interview'
import { ElMessage, ElMessageBox, FormInstance, UploadProps } from 'element-plus'
import { getTimeInfoService } from '@/apis/timeManage'
import { getToken } from '@/utils/token'
import { getAllClassNameService } from '@/apis/dataCount'

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(30)
const dialogDetailVisible = ref(false)
const dialogScoreVisible = ref(false)
const diaForm = ref({})
const scoreFormRef = ref<FormInstance>()
const multipleSelection = ref([])
const token = { token: getToken() }
const selectIds = ref([])
const classNameList = ref([])
const sortByStuGrade = (k: any) => {
  for (let i = 0; i < intvInfoData.value.length; i++) {
    if (intvInfoData.value[i].stuGrade === '大一') intvInfoData.value[i].gradeKey = 1
    if (intvInfoData.value[i].stuGrade === '大二') intvInfoData.value[i].gradeKey = 2
    if (intvInfoData.value[i].stuGrade === '大三') intvInfoData.value[i].gradeKey = 3
    if (intvInfoData.value[i].stuGrade === '大四') intvInfoData.value[i].gradeKey = 4
  }
  if (k.order === 'ascending') {
    intvInfoData.value.sort((a, b) => (a.gradeKey > b.gradeKey ? 1 : -1))
  }
  if (k.order === 'descending') {
    intvInfoData.value.sort((a, b) => (a.gradeKey > b.gradeKey ? -1 : 1))
  }
}
const intvScoreInfo = ref({
  studentId: '',
  intvId: '',
  intvScore: '',
  intvState: ''
})

const searchIntv = ref({
  studentId: '',
  stuName: '',
  className: '',
  intvDate: '',
  intvState: '未面试',
  intvScore: ''
})
const intvTime = ref({
  intvStartDate: '',
  intvEndDate: '',
  intvStartTime: '',
  intvEndTime: ''
})
const intvInfoData = ref([])
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
    ElMessage.error('只能上传 xlsx 格式文件!')
    return false
  }
  return true
}
const successUpload: UploadProps['onSuccess'] = (response) => {
  if (response.code == 0) ElMessage.error(response.msg)
  else {
    ElMessage({ type: 'success', message: '导入成功' })
    page()
  }
}
const handleClick = () => {
  page()
}
const getTime = () => {
  getTimeInfoService().then((res) => {
    if (res.data.code === 1) {
      intvTime.value = res.data.data
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

onMounted(() => {
  getAllClassNameService().then((res) => {
    if (res.data.code === 1) {
      let className = res.data.data
      for (let v of className) {
        classNameList.value.push({ value: v })
      }
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
  page()
  getTime()
})
const page = () => {
  if (searchIntv.value.intvDate != '') searchIntv.value.intvDate = Format(searchIntv.value.intvDate)
  getIntvInfo(
    currentPage.value,
    pageSize.value,
    searchIntv.value.studentId,
    searchIntv.value.stuName,
    searchIntv.value.className,
    searchIntv.value.intvDate,
    searchIntv.value.intvState,
    searchIntv.value.intvScore
  ).then((res) => {
    if (res.data.code === 1) {
      intvInfoData.value = res.data.data.rows
      total.value = res.data.data.total
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
}
const passByIntvIds = () => {
  if (multipleSelection.value === null || multipleSelection.value.length === 0) {
    ElMessage({ type: 'error', message: '未选择通过人员' })
    return false
  }
  ElMessageBox.confirm('确认该批学生通过面试吗？', '提醒', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(() => {
      for (let i = 0; i < multipleSelection.value.length; i++) {
        selectIds.value[i] = multipleSelection.value[i].intvId
      }
      passByIds(selectIds.value).then((res) => {
        if (res.data.code === 1) {
          ElMessage({ type: 'success', message: '操作成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {})
}
const noPassByIntvIds = () => {
  if (multipleSelection.value === null || multipleSelection.value.length === 0) {
    ElMessage({ type: 'error', message: '未选择通过人员' })
    return false
  }
  ElMessageBox.confirm('确认该批学生不通过面试吗？', '提醒', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(() => {
      for (let i = 0; i < multipleSelection.value.length; i++) {
        selectIds.value[i] = multipleSelection.value[i].intvId
      }
      noPassByIds(selectIds.value).then((res) => {
        if (res.data.code === 1) {
          ElMessage({ type: 'success', message: '操作成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {})
}
const handleSelectionChange = (val: number[]) => {
  multipleSelection.value = val
}
const submitForm = () => {
  currentPage.value = 1
  page()
}

const exportIntvInfo = async () => {
  if (searchIntv.value.className === '') {
    ElMessage({ type: 'error', message: '请选择导出哪一届卓越班学生面试信息' })
    return
  }
  const { data } = await ExportIntvInfo(searchIntv.value.intvState, searchIntv.value.className)
  let url = window.URL.createObjectURL(data)
  var a = document.createElement('a')
  document.body.appendChild(a)
  a.href = url
  a.download = '面试人员信息表.xlsx'
  a.click()
  window.URL.revokeObjectURL(url)
}
const resetForm = () => {
  searchIntv.value = {
    studentId: '',
    stuName: '',
    className: '',
    intvDate: '',
    intvState: searchIntv.value.intvState,
    intvScore: 0
  }
  page()
}

const SizeChange = (val: number) => {
  pageSize.value = val
  page()
}
const CurrentChange = (val: number) => {
  currentPage.value = val
  page()
}

const goDetail = (row: any) => {
  diaForm.value = {}
  dialogDetailVisible.value = true
  diaForm.value = { ...row }
}
const setScore = (row: any) => {
  dialogScoreVisible.value = true
  intvScoreInfo.value.intvScore = { ...row }.intvScore
  intvScoreInfo.value.intvId = { ...row }.intvId
  intvScoreInfo.value.studentId = { ...row }.studentId
}
const submitScore = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      intvScoreInfo.value.intvState = '已面试'
      setIntvScore(intvScoreInfo.value).then((res) => {
        if (res.data.code === 1) {
          intvScoreInfo.value = {}
          dialogScoreVisible.value = false
          ElMessage({ type: 'success', message: '打分成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    } else {
      return false
    }
  })
}
const Return = (row: any) => {
  ElMessageBox({
    title: '提醒',
    message: h('p', null, [
      h('span', null, '撤回后该学生考试状态将改为 '),
      h('strong', { style: 'color: #E6A23C' }, '已面试'),
      h('span', null, ' 确定撤回吗?')
    ]),
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    showCancelButton: true,
    center: true,
    type: 'warning'
  })
    .then(() => {
      intvScoreInfo.value.intvId = { ...row }.intvId
      intvScoreInfo.value.intvScore = { ...row }.intvScore
      intvScoreInfo.value.studentId = { ...row }.studentId
      intvScoreInfo.value.intvState = '已面试'
      setIntvScore(intvScoreInfo.value).then((res) => {
        if (res.data.code === 1) {
          intvScoreInfo.value = {}
          dialogScoreVisible.value = false
          ElMessage({ type: 'success', message: '撤回成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {})
}
const pass = (row: any) => {
  ElMessageBox.confirm('确认该学生通过面试吗?', '提醒', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(() => {
      intvScoreInfo.value.intvId = { ...row }.intvId
      intvScoreInfo.value.studentId = { ...row }.studentId
      if ({ ...row }.intvScore === '' || { ...row }.intvScore === null) {
        ElMessage({ type: 'error', message: '还未打分，无法通过面试' })
        return false
      }
      intvScoreInfo.value.intvScore = { ...row }.intvScore
      intvScoreInfo.value.intvState = '已通过'
      setIntvScore(intvScoreInfo.value).then((res) => {
        if (res.data.code === 1) {
          intvScoreInfo.value = {}
          dialogScoreVisible.value = false
          ElMessage({ type: 'success', message: '设置成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {})
}
const noPass = (row: any) => {
  ElMessageBox.confirm('确认该学生未通过面试吗?', '提醒', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(() => {
      intvScoreInfo.value.intvId = { ...row }.intvId
      intvScoreInfo.value.intvScore = { ...row }.intvScore
      intvScoreInfo.value.studentId = { ...row }.studentId
      intvScoreInfo.value.intvState = '未通过'
      setIntvScore(intvScoreInfo.value).then((res) => {
        if (res.data.code === 1) {
          intvScoreInfo.value = {}
          dialogScoreVisible.value = false
          ElMessage({ type: 'success', message: '设置成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {})
}
function Format(date) {
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  if (month < 10) month = '0' + month
  if (day < 10) day = '0' + day
  return year + '-' + month + '-' + day
}
const intvDisabledDateFun = (date: Date) => {
  if (Format(date) >= intvTime.value.intvStartDate && Format(date) <= intvTime.value.intvEndDate)
    return false
  return true
}
</script>
<style>
.info-box {
  margin: -15px -10px 20px;
}
.info-box .item-box {
  height: 20px;
  line-height: 50px;
  font-size: 14px;
  font-weight: 400;
  color: #666666;
  text-align: left;
  margin-bottom: 14px;
}
.info-box .item-box .label {
  width: 50px;
  margin-left: 40px;
}
.info-box .item-box .des {
  color: #333333;
}
</style>
